package com.c2b.algorithm.leetcode.base;

/**
 * <a href="https://leetcode.cn/problems/add-binary/description/?envType=study-plan-v2&envId=top-interview-150/">二进制求和(Add Binary)</a>
 * <p>给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入:a = "11", b = "1"
 *      输出："100"
 *
 * 示例 2：
 *      输入：a = "1010", b = "1011"
 *      输出："10101"
 * </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 *  <ul>
 *     <li>1 <= a.length, b.length <= 10^4</li>
 *     <li>a 和 b 仅由字符 '0' 或 '1' 组成</li>
 *     <li>字符串如果不是 "0" ，就不含前导零</li>
 *  </ul>
 * </p>
 *
 * @author c2b
 * @since 2022/5/18 14:08
 */
public class LC0067AddBinary_S {

    static class Solution {
        public String addBinary(String a, String b) {
            int aIndex = a.length()-1;
            int bIndex = b.length()-1;
            int carry = 0;
            StringBuilder ret = new StringBuilder();
            while (aIndex >= 0 || bIndex >= 0) {
                // 如果a没走完
                carry = carry + (aIndex >= 0 ? a.charAt(aIndex--) - '0' : 0);
                // 如果b没走完
                carry = carry + (bIndex >= 0 ? b.charAt(bIndex--) - '0' : 0);
                ret.append(carry % 2);
                carry >>= 1;
            }
            if (carry == 1) {
                ret.append("1");
            }
            return ret.reverse().toString();
        }
    }
}
